package org.auf.core;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.auf.model.User;
import org.auf.model.UserDAOJDBC;

import org.apache.log4j.Logger; 

/**
 * Servlet implementation class for Servlet: FrontController
 *
 */
 public class FrontController extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

	private static final long serialVersionUID = 6835833064236425655L;
	private static String ATTRIBUTE_ACTION= "action"; 
	
	static Logger log = Logger.getLogger(FrontController.class.getName()); 
	 
	@Override
	public void init(ServletConfig config) throws ServletException {
		ControllerFactory.getInstance().init(this);
		ScoreTimer.execute();
	}


	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		log.info("Peticion realizada");
		
		ControllerFactory controllerFactory = ControllerFactory.getInstance();
		
		String action = (String)request.getAttribute(ATTRIBUTE_ACTION);
		Controller controller = controllerFactory.create(action);
		
		if (controller == null) {
			log.error("No se encontro el controlador '" + action + "'" );
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}
		
		controller.assignThread(request, response, this);
		
		if (controller.getPrivileges() == Privileges.PUBLIC) {
			controller.show();
			return;
		}
		
		HttpSession session = request.getSession(false);
		
		if (session == null) {
			log.info("No hay sesion, mostrando la pagina de login");
			controller = controllerFactory.create("login");
			controller.assignThread(request, response, this);
			controller.show();
			return;
		}
		
		User user = UserDAOJDBC.getInstance().selectUserByid((String)session.getAttribute("id"));
		
		if (user == null || ( controller.getPrivileges() == Privileges.ADMIN /*&& !(user instanceof Admin)*/)) {
			log.info("Esta tratando de acceder a un controlador para el cual no tiene privilegios.");
			response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
			return;
		}
		
		//Asignamos las variables globales al layout
		IView view = controller.getView();
		view.assignVar("user", user);
		controller.setUser(user);
		
		controller.show();
	}
	
}